package com.lwl.concurrency.executor;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.*;

/**<pre>
 * 运行多个任务并处理第一个结果
 * 并发编程比较常见的一个问题是,当采用多个并发任务来
 * 解决一个问题时,往往只关心这些任务中的第一个结果.
 * 比如对一个数组进行排序有很多种算法,可以并发启动所有算法
 * 第一个得到排序结果的算法就是最快的排序算法
 * </pre>
 * Created by liwenlong on 2018/1/7 19:16
 */
public class UseFirstResultTest {

    static class UserValidator{
        private String name;

        UserValidator(String name){
            this.name = name;
        }

        boolean validate(String name,String password){
            Random random = new Random();
            int duration = random.nextInt(10);
            System.out.printf("%s validator %s: validating a user during %d seconds\n",
                    Thread.currentThread().getName(),
                    this.name,duration);
            try {
                TimeUnit.SECONDS.sleep(duration);
            } catch (InterruptedException e) {
                e.printStackTrace();
                return false;
            }
            return random.nextBoolean();
        }

        public String getName() {
            return name;
        }
    }

    static public class TaskValidator implements Callable<String>{
        private UserValidator validator;
        private String user;
        private String password;

        TaskValidator(UserValidator validator, String user, String password) {
            this.validator = validator;
            this.user = user;
            this.password = password;
        }

        @Override
        public String call() throws Exception {
            if(!validator.validate(user,password)){
                System.out.printf("%s: the user has not been found\n",validator.getName());
                throw new Exception("error validating user");
            }
            System.out.printf("%s: the user has been found\n",validator.getName());
            return validator.getName();
        }
    }


    public static void main(String[] args) {
        String username = "test";
        String password = "test";

        UserValidator ldapValidator = new UserValidator("ldap");
        UserValidator dbValidator = new UserValidator("db");

        TaskValidator ldapTask = new TaskValidator(ldapValidator,username,password);
        TaskValidator dbTask = new TaskValidator(dbValidator,username,password);

        List<TaskValidator> taskList = new ArrayList<>();
        taskList.add(ldapTask);
        taskList.add(dbTask);

        ExecutorService executorService = Executors.newCachedThreadPool();
        try {
            //返回第一个完成任务,并且没有抛出异常的任务的执行结果
            String s = executorService.invokeAny(taskList);
            System.out.println("main result :"+s);
        } catch (InterruptedException e) {
            System.out.println("异常抛出11111111111");
            e.printStackTrace();
        } catch (ExecutionException e) {
            System.out.println("异常抛出22222222222");
            e.printStackTrace();
        }
        System.out.println("马上执行shutdown()");
        executorService.shutdown();
        System.out.println("Main: End of the execution");
    }






}
